package com.cmcc.linlaker;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.android.volley.VolleyError;
import com.cmcc.linlaker.application.LinhuApp;
import com.cmcc.linlaker.bean.AreaListBean;
import com.cmcc.linlaker.bean.BaseBean;
import com.cmcc.linlaker.bean.DepartmentListBean;
import com.cmcc.linlaker.bean.DictBean;
import com.cmcc.linlaker.fragment.MineFragment;
import com.cmcc.linlaker.fragment.QueryFragment;
import com.cmcc.linlaker.fragment.RoundFragment;
import com.cmcc.linlaker.fragment.UploadFragment;
import com.cmcc.linlaker.http.ApiDefine;
import com.cmcc.linlaker.service.GohnsonService;
import com.cmcc.linlaker.ui.upload.NewUploadQuestionActivity2;
import com.cmcc.linlaker.utils.BarUtils;
import com.cmcc.linlaker.utils.BottomNavigationViewHelper;
import com.cmcc.linlaker.utils.IntentUtils;
import com.cmcc.linlaker.utils.SPHelper;
import com.cmcc.linlaker.utils.ToastUtils;
import com.cmcc.linlaker.volley.GsonRequestHelper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

public class MainActivity extends AppCompatActivity {
    private BottomNavigationView mBottomNavigationView;

    private int lastIndex;
    List<Fragment> mFragments;
    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        BarUtils.initStatusBar(this);

//        setAlpha();
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("正在请求字典数据...");
        initView();

        startService(new Intent(this, GohnsonService.class));
    }

    public void setAlpha() {
        WindowManager.LayoutParams lp = getWindow()
                .getAttributes();
        lp.alpha = 1f;
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        getWindow().setAttributes(lp);
    }

    public void initView() {
        getCurrentLocationLatLng();
        mHandler.postDelayed(r, 5000);//延时100毫秒

        progressDialog.show();
        projectTypeDict();
        departmentList();
        feedbackTypeDict();
    }

    //声明AMapLocationClient类对象
    private AMapLocationClient mLocationClient = null;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;

    /**
     * 初始化定位并设置定位回调监听
     */
    private void getCurrentLocationLatLng() {
        //初始化定位
        mLocationClient = new AMapLocationClient(this);
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        // 同时使用网络定位和GPS定位,优先返回最高精度的定位结果,以及对应的地址描述信息
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置定位间隔,单位毫秒,默认为2000ms，最低1000ms。默认连续定位 切最低时间间隔为1000ms
        mLocationOption.setOnceLocation(false);
        mLocationOption.setInterval(5000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    private double latitude, longitude;
    /**
     * 定位回调监听器
     */
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    //定位成功回调信息，设置相关消息
                    amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                    latitude = amapLocation.getLatitude();//获取纬度
                    longitude = amapLocation.getLongitude();//获取经度
                } else {
                }
            }
        }
    };


    Handler mHandler = new Handler();
    Runnable r = new Runnable() {
        @Override
        public void run() {
            //上传经纬度
            uploadGps();
            //每隔1s循环执行run方法
            mHandler.postDelayed(this, 15000);
        }
    };

    /**
     * 上传经纬度
     */
    private void uploadGps() {
        GsonRequestHelper helper = new GsonRequestHelper(this);
        Map<String, String> params = new HashMap<>();
        params.put("latitude", latitude + "");
        params.put("longitude", longitude + "");

        params.put("userId", SPHelper.getUid());
        helper.sendPOSTRequest(ApiDefine.UPLOAD_GPS, BaseBean.class, params, false, null);
        helper.setOnResponseListener(new GsonRequestHelper.OnResponseListener() {
            @Override
            public void onError(VolleyError error) {

            }

            @Override
            public void onSuccess(Object data) {
                if (data != null) {
                    BaseBean bean = (BaseBean) data;
                    if (bean.code.equals(IntentUtils.VAILD_CODE)) {
                        IntentUtils.skipToLogin(MainActivity.this);
                    }
                }
            }
        });
    }

    /**
     * 处置结果
     */
    public void feedbackTypeDict() {
        GsonRequestHelper helper = new GsonRequestHelper(this);
        Map<String, String> params = new HashMap<>();
        params.put("dictType", "feed_back_result");

        helper.sendPOSTRequest(ApiDefine.PROJECT_DICT, DictBean.class, params, false, null);
        helper.setOnResponseListener(new GsonRequestHelper.OnResponseListener() {
            @Override
            public void onError(VolleyError error) {

            }

            @Override
            public void onSuccess(Object data) {
                if (data != null) {
                    DictBean bean = (DictBean) data;

                    if (bean.code.equals("0")) {
                        List<DictBean.DictData> list = bean.rows;
                        if (list != null && list.size() > 0) {
                            LinhuApp.feedbackList.clear();
                            LinhuApp.feedbackList.addAll(list);
                        }
                    } else if (bean.code.equals(IntentUtils.VAILD_CODE)) {
                        IntentUtils.skipToLogin(MainActivity.this);
                    }
                }
            }
        });
    }

    /**
     * 审批部门
     */
    public void departmentList() {
        Map<String, String> params = new HashMap<>();
//        params.put("deptType", "2");
        Map<String, String> headers = new HashMap<>();
        headers.put("authToken", SPHelper.getAuthToken());
        headers.put("from", "android");
        OkHttpUtils.post().headers(headers).params(params).url(ApiDefine.DEPARTMENT_LIST).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String s, int id) {
                String jsonStr = s;

                Gson gson = new GsonBuilder().create();
                List<DepartmentListBean.DepartmentData> list = gson.fromJson(jsonStr, new TypeToken<List<DepartmentListBean.DepartmentData>>() {
                }.getType());

                if (list != null && list.size() > 0) {
                    LinhuApp.departmentList.clear();
                    LinhuApp.departmentList.addAll(list);
                }
            }
        });
    }

    /**
     * 项目类型
     */
    public void projectTypeDict() {
        GsonRequestHelper helper = new GsonRequestHelper(this);
        Map<String, String> params = new HashMap<>();
        params.put("dictType", "project_type");

        helper.sendPOSTRequest(ApiDefine.PROJECT_DICT, DictBean.class, params, false, null);
        helper.setOnResponseListener(new GsonRequestHelper.OnResponseListener() {
            @Override
            public void onError(VolleyError error) {

            }

            @Override
            public void onSuccess(Object data) {
                if (data != null) {
                    DictBean bean = (DictBean) data;

                    if (bean.code.equals("0")) {
                        List<DictBean.DictData> list = bean.rows;
                        if (list != null && list.size() > 0) {
                            LinhuApp.typeList.clear();
                            LinhuApp.typeList.addAll(list);

                            projectUsingAttributesDict();
                        }
                    } else if (bean.code.equals(IntentUtils.VAILD_CODE)) {
                        IntentUtils.skipToLogin(MainActivity.this);
                    }
                }
            }
        });
    }

    /**
     * 建设性质
     */
    public void projectNatureDict() {
        GsonRequestHelper helper = new GsonRequestHelper(this);
        Map<String, String> params = new HashMap<>();
        params.put("dictType", "nature");

        helper.sendPOSTRequest(ApiDefine.PROJECT_DICT, DictBean.class, params, false, null);
        helper.setOnResponseListener(new GsonRequestHelper.OnResponseListener() {
            @Override
            public void onError(VolleyError error) {

            }

            @Override
            public void onSuccess(Object data) {
                if (data != null) {
                    DictBean bean = (DictBean) data;

                    if (bean.code.equals("0")) {
                        List<DictBean.DictData> list = bean.rows;
                        if (list != null && list.size() > 0) {
                            LinhuApp.natureList.clear();
                            LinhuApp.natureList.addAll(list);

                            problemTypeDict();
                        }
                    } else if (bean.code.equals(IntentUtils.VAILD_CODE)) {
                        IntentUtils.skipToLogin(MainActivity.this);
                    }
                }
            }
        });
    }

    /**
     * 问题类型
     */
    public void problemTypeDict() {
        GsonRequestHelper helper = new GsonRequestHelper(this);
        Map<String, String> params = new HashMap<>();
        params.put("dictType", "problem_type");

        helper.sendPOSTRequest(ApiDefine.PROJECT_DICT, DictBean.class, params, false, null);
        helper.setOnResponseListener(new GsonRequestHelper.OnResponseListener() {
            @Override
            public void onError(VolleyError error) {

            }

            @Override
            public void onSuccess(Object data) {
                if (data != null) {
                    DictBean bean = (DictBean) data;

                    if (bean.code.equals("0")) {
                        List<DictBean.DictData> list = bean.rows;
                        if (list != null && list.size() > 0) {
                            LinhuApp.problemTypeList.clear();
                            LinhuApp.problemTypeList.addAll(list);

                            progressDialog.dismiss();
                            initBottomNavigation();
                            initData();
                        }
                    } else if (bean.code.equals(IntentUtils.VAILD_CODE)) {
                        IntentUtils.skipToLogin(MainActivity.this);
                    }
                }
            }
        });
    }

    /**
     * 建设形式
     */
    public void projectFormDict() {
        GsonRequestHelper helper = new GsonRequestHelper(this);
        Map<String, String> params = new HashMap<>();
        params.put("dictType", "construction_form");

        helper.sendPOSTRequest(ApiDefine.PROJECT_DICT, DictBean.class, params, false, null);
        helper.setOnResponseListener(new GsonRequestHelper.OnResponseListener() {
            @Override
            public void onError(VolleyError error) {

            }

            @Override
            public void onSuccess(Object data) {
                if (data != null) {
                    DictBean bean = (DictBean) data;

                    if (bean.code.equals("0")) {
                        List<DictBean.DictData> list = bean.rows;
                        if (list != null && list.size() > 0) {
                            LinhuApp.formList.clear();
                            LinhuApp.formList.addAll(list);

                            projectNatureDict();
                        }
                    } else if (bean.code.equals(IntentUtils.VAILD_CODE)) {
                        IntentUtils.skipToLogin(MainActivity.this);
                    }
                }
            }
        });
    }

    /**
     * 建设状态
     */
    public void projectStateDict() {
        GsonRequestHelper helper = new GsonRequestHelper(this);
        Map<String, String> params = new HashMap<>();
        params.put("dictType", "project_states");

        helper.sendPOSTRequest(ApiDefine.PROJECT_DICT, DictBean.class, params, false, null);
        helper.setOnResponseListener(new GsonRequestHelper.OnResponseListener() {
            @Override
            public void onError(VolleyError error) {

            }

            @Override
            public void onSuccess(Object data) {
                if (data != null) {
                    DictBean bean = (DictBean) data;

                    if (bean.code.equals("0")) {
                        List<DictBean.DictData> list = bean.rows;
                        if (list != null && list.size() > 0) {
                            LinhuApp.stateList.clear();
                            LinhuApp.stateList.addAll(list);

                            projectFormDict();
                        }
                    } else if (bean.code.equals(IntentUtils.VAILD_CODE)) {
                        IntentUtils.skipToLogin(MainActivity.this);
                    }
                }
            }
        });
    }

    /**
     * 项目使用属性
     */
    public void projectUsingAttributesDict() {
        GsonRequestHelper helper = new GsonRequestHelper(this);
        Map<String, String> params = new HashMap<>();
        params.put("dictType", "using_attributes");

        helper.sendPOSTRequest(ApiDefine.PROJECT_DICT, DictBean.class, params, false, null);
        helper.setOnResponseListener(new GsonRequestHelper.OnResponseListener() {
            @Override
            public void onError(VolleyError error) {

            }

            @Override
            public void onSuccess(Object data) {
                if (data != null) {
                    DictBean bean = (DictBean) data;

                    if (bean.code.equals("0")) {
                        List<DictBean.DictData> list = bean.rows;
                        if (list != null && list.size() > 0) {
                            LinhuApp.usingAttributesList.clear();
                            LinhuApp.usingAttributesList.addAll(list);

                            projectProcessStatusDict();
                        }
                    } else if (bean.code.equals(IntentUtils.VAILD_CODE)) {
                        IntentUtils.skipToLogin(MainActivity.this);
                    }
                }
            }
        });
    }

    /**
     * 所属行业
     */
    public void projectIndustryDict() {
        GsonRequestHelper helper = new GsonRequestHelper(this);
        Map<String, String> params = new HashMap<>();
        params.put("dictType", "industry");

        helper.sendPOSTRequest(ApiDefine.PROJECT_DICT, DictBean.class, params, false, null);
        helper.setOnResponseListener(new GsonRequestHelper.OnResponseListener() {
            @Override
            public void onError(VolleyError error) {

            }

            @Override
            public void onSuccess(Object data) {
                if (data != null) {
                    DictBean bean = (DictBean) data;

                    if (bean.code.equals("0")) {
                        List<DictBean.DictData> list = bean.rows;
                        if (list != null && list.size() > 0) {
                            LinhuApp.industryList.clear();
                            LinhuApp.industryList.addAll(list);

                            projectStateDict();
                        }
                    } else if (bean.code.equals(IntentUtils.VAILD_CODE)) {
                        IntentUtils.skipToLogin(MainActivity.this);
                    }
                }
            }
        });
    }

    /**
     * 保护区,是否管控,是否整治项目
     */
    public void projectIsDict() {
        GsonRequestHelper helper = new GsonRequestHelper(this);
        Map<String, String> params = new HashMap<>();
        params.put("dictType", "is_flag");

        helper.sendPOSTRequest(ApiDefine.PROJECT_DICT, DictBean.class, params, false, null);
        helper.setOnResponseListener(new GsonRequestHelper.OnResponseListener() {
            @Override
            public void onError(VolleyError error) {

            }

            @Override
            public void onSuccess(Object data) {
                if (data != null) {
                    DictBean bean = (DictBean) data;

                    if (bean.code.equals("0")) {
                        List<DictBean.DictData> list = bean.rows;
                        if (list != null && list.size() > 0) {
                            LinhuApp.isList.clear();
                            LinhuApp.isList.addAll(list);

                            projectIndustryDict();
                        }
                    } else if (bean.code.equals(IntentUtils.VAILD_CODE)) {
                        IntentUtils.skipToLogin(MainActivity.this);
                    }
                }
            }
        });
    }

    /**
     * 办理状态
     */
    public void projectProcessStatusDict() {
        GsonRequestHelper helper = new GsonRequestHelper(this);
        Map<String, String> params = new HashMap<>();
        params.put("dictType", "process_status");

        helper.sendPOSTRequest(ApiDefine.PROJECT_DICT, DictBean.class, params, false, null);
        helper.setOnResponseListener(new GsonRequestHelper.OnResponseListener() {
            @Override
            public void onError(VolleyError error) {

            }

            @Override
            public void onSuccess(Object data) {
                if (data != null) {
                    DictBean bean = (DictBean) data;

                    if (bean.code.equals("0")) {
                        List<DictBean.DictData> list = bean.rows;
                        if (list != null && list.size() > 0) {
                            LinhuApp.processStatusList.clear();
                            LinhuApp.processStatusList.addAll(list);

                            resetList();
                            regionDict();
                        }
                    } else if (bean.code.equals(IntentUtils.VAILD_CODE)) {
                        IntentUtils.skipToLogin(MainActivity.this);
                    }
                }
            }
        });
    }

    /**
     * 重置
     */
    private void resetList() {
        for (int i = 0; i < LinhuApp.processStatusList.size(); i++) {
            if (i == 0) {
                LinhuApp.processStatusList.get(i).isSelected = true;
            } else {
                LinhuApp.processStatusList.get(i).isSelected = false;
            }
        }

        for (int i = 0; i < LinhuApp.usingAttributesList.size(); i++) {
            if (i == 0) {
                LinhuApp.usingAttributesList.get(i).isSelected = true;
            } else {
                LinhuApp.usingAttributesList.get(i).isSelected = false;
            }
        }

        for (int i = 0; i < LinhuApp.typeList.size(); i++) {
            if (i == 0) {
                LinhuApp.typeList.get(i).isSelected = true;
            } else {
                LinhuApp.typeList.get(i).isSelected = false;
            }
        }
    }

    /**
     * 所属地区
     */
    public void regionDict() {
        Map<String, String> params = new HashMap<>();
        params.put("deptType", "1");
        Map<String, String> headers = new HashMap<>();
        headers.put("authToken", SPHelper.getAuthToken());
        headers.put("from", "android");
        OkHttpUtils.post().headers(headers).params(params).url(ApiDefine.AREA_LIST).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String s, int id) {
                String jsonStr = s;
                Gson gson = new GsonBuilder().create();
                AreaListBean list = gson.fromJson(jsonStr, new TypeToken<AreaListBean>() {
                }.getType());

                if (list.rows != null && list.rows.size() > 0) {
                    LinhuApp.regionList.clear();
                    LinhuApp.regionList.addAll(list.rows);

                    projectIsDict();
                }
            }
        });
    }

    private void resetToDefaultIcon() {
        MenuItem menu_round = mBottomNavigationView.getMenu().findItem(R.id.menu_round);
        menu_round.setIcon(R.mipmap.bottom_tab_round_unselected);

        MenuItem menu_upload = mBottomNavigationView.getMenu().findItem(R.id.menu_upload);
        menu_upload.setIcon(R.mipmap.bottom_tab_upload_unselected);

        MenuItem menu_query = mBottomNavigationView.getMenu().findItem(R.id.menu_query);
        menu_query.setIcon(R.mipmap.bottom_tab_query_unselected);

        MenuItem menu_mine = mBottomNavigationView.getMenu().findItem(R.id.menu_mine);
        menu_mine.setIcon(R.mipmap.bottom_tab_mine_unselected);
    }

    public void initData() {
        mFragments = new ArrayList<>();
        mFragments.add(new RoundFragment());
        mFragments.add(new UploadFragment());
        mFragments.add(new QueryFragment());
        mFragments.add(new MineFragment());

        // 初始化展示
        setFragmentPosition(0);
        MenuItem menu_round = mBottomNavigationView.getMenu().findItem(R.id.menu_round);
        menu_round.setIcon(R.mipmap.bottom_tab_round_selected);

        BarUtils.setStatusBarTextColor(MainActivity.this, false);
    }

    public void initBottomNavigation() {
        mBottomNavigationView = findViewById(R.id.bv_bottomNavigation);
        mBottomNavigationView.setItemIconTintList(null);
        // 解决当item大于三个时，非平均布局问题
        BottomNavigationViewHelper.disableShiftMode(mBottomNavigationView);
        mBottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                resetToDefaultIcon();//重置到默认不选中图片
                switch (item.getItemId()) {
                    case R.id.menu_round:
                        setFragmentPosition(0);
                        BarUtils.setStatusBarTextColor(MainActivity.this, false);
                        item.setIcon(R.mipmap.bottom_tab_round_selected);
                        break;
                    case R.id.menu_upload:
                        setFragmentPosition(1);
                        BarUtils.setStatusBarTextColor(MainActivity.this, false);
                        item.setIcon(R.mipmap.bottom_tab_upload_selected);
                        break;
                    case R.id.menu_query:
                        setFragmentPosition(2);
                        BarUtils.setStatusBarTextColor(MainActivity.this, false);
                        item.setIcon(R.mipmap.bottom_tab_query_selected);
                        break;
                    case R.id.menu_mine:
                        setFragmentPosition(3);
                        BarUtils.setStatusBarTextColor(MainActivity.this, false);
                        item.setIcon(R.mipmap.bottom_tab_mine_selected);
                        break;
                    default:
                        break;
                }
                // 这里注意返回true,否则点击失效
                return true;
            }
        });
    }


    private void setFragmentPosition(int position) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        Fragment currentFragment = mFragments.get(position);
        Fragment lastFragment = mFragments.get(lastIndex);
        lastIndex = position;
        ft.hide(lastFragment);
        if (!currentFragment.isAdded()) {
            getSupportFragmentManager().beginTransaction().remove(currentFragment).commit();
            ft.add(R.id.ll_frameLayout, currentFragment);
        }
        ft.show(currentFragment);
        ft.commitAllowingStateLoss();
    }

    private long mExitTime;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {// 如果两次按键时间间隔大于2000毫秒，则不退出
                ToastUtils.showText(this, "再按一次退出淳安智慧城管");
                mExitTime = System.currentTimeMillis();// 更新mExitTime
            } else {

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        finish();
                        System.exit(0);// 否则退出程序
                    }
                }, 300);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void upload(View view) {
        Intent intent = new Intent(MainActivity.this, NewUploadQuestionActivity2.class);
        startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        mHandler.removeCallbacks(r);
    }
}
